﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI;
using System.IO;
using System.Text;
using System.Globalization;
using RazorBridge.Helpers;

namespace RazorBridge.Mvc
{
    public static class RenderPartialView
    {
        public static string RenderPartialViewToString(this ControllerBase controller, string pluginKey, string viewKey, object model)
        {
            controller.ViewData.Model = model;
            try
            {
                using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture))
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, FrameworkUtility.CreateCombinedViewName(pluginKey, viewKey));
                    if (viewResult != null)
                    {
                        ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                        if (viewContext != null)
                        {
                            viewResult.View.Render(viewContext, sw);                            
                        }
                    }
                    
                    return sw.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }
    }
}